const express = require("express");
const fs = require("fs");
const path = require("path");

const server = express();
// 获取 访问主机的 ip 地址
function getClientIp(req) {
    return req.headers['x-forwarded-for'] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress;
}

server.use((req, res, next) => {
    // getClientIp(req);
    let dt = new Date();
    console.log('now time = ', dt.toLocaleTimeString());
    req.time = dt.toLocaleTimeString();
    console.log(req.url);
    req.urlPath = req.url;
    console.log("from ", getClientIp(req));
    req.ipFrom = getClientIp(req);
    next();
})


server.use((req, res) => {
    const filePath = path.join(__dirname, "log.txt");
    // let info = {
    //     time: req.time,
    //     url: req.urlPath,
    //     ip: req.ipFrom
    // }
    let info =
        `
    访问时间：${req.time}
    访问路径：${req.urlPath},
    访问主机地址：${req.ipFrom}
    `
    fs.appendFileSync(filePath, info);
    res.end("over");
})

server.listen(8001, () => {
    console.log('ok');
})